<template>
  <div class="create-post-page">
    <h4>新建文章</h4>
    <UploaderFile
      action="/upload"
      class="d-flex align-items-center justify-content-center bg-light text-secondary w100 my-4"
      :beforeUpload="uploadedCheck"
      @file-uploaded="handleFileUploaded"
    >
      <h2>点击上传头图</h2>
      <template #loading>
        <div class="d-flex">
          <div class="spinner-border text-secondary" roule="status">
            <!-- <span class="scr-only">Loading...</span> -->
          </div>
        </div>
        <h2>正在上传</h2>
      </template>
      <template #uploaded="dataProps">
        <div class="uploaded-area">
          <img :src="dataProps.uploadedData.data.url" />
          <h3>点击重新上传</h3>
        </div>
      </template>
    </UploaderFile>
    <!-- <input type="file" name="file" @change.prevent="handleFileChange" /> -->
    <ValidateForm @form-submit="onFormSubmit">
      <div class="mb-3">
        <label for="" class="form-label">文章标题:</label>
        <ValidateInput
          placeholder="请输入文章标题"
          type="text"
          :rules="titleRules"
          v-model="titleVal"
          @value="titleValue"
        ></ValidateInput>
      </div>
      <div class="mb-3">
        <label for="" class="form-label">文章详情:</label>
        <ValidateInput
          placeholder="请输入文章详情"
          rows="10"
          tag="textarea"
          type="text"
          @value="contentValue"
          v-model="contentVal"
          :rules="contentRules"
        ></ValidateInput>
      </div>
      <template #submit>
        <button class="btn btn-primary btn-large">发表文章</button>
      </template>
    </ValidateForm>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from "vue";
import { useStore } from "vuex";
import axios from "axios";
import {
  GolbalDataProps,
  UserProps,
  ResponseType,
  ImageProps,
  PostProps,
} from "@/store";
import { useRoute, useRouter } from "vue-router";
import ValidateForm from "./ValidateForm.vue";
import ValidateInput, { RulesProp } from "./ValidateInput.vue";
import UploaderFile from "./UploaderFile.vue";
import { beforUpLoadCheck } from "@/hooks/helper";
import createMessage from "@/hooks/createMessage";

export default defineComponent({
  name: "CreatePost",
  components: {
    ValidateForm,
    ValidateInput,
    UploaderFile,
  },
  setup() {
    const titleVal = ref("");
    const titleValue = (val: string) => {
      titleVal.value = val;
    };
    const router = useRouter();
    const store = useStore<GolbalDataProps>();
    const titleRules: RulesProp = [
      { type: "required", message: "文章标题不能为空" },
    ];

    const contentVal = ref("");
    const contentValue = (val: string) => {
      contentVal.value = val;
    };
    const contentRules: RulesProp = [
      { type: "required", message: "文章详情不能为空" },
    ];

    let imageId = "";

    // 验证图片的格式和大小是否正确
    const uploadedCheck = (file: File) => {
      const result = beforUpLoadCheck(file, {
        format: ["image/jpeg", "image.png"],
        size: 1,
      });
      const { passed, error } = result;
      // 根据不同的类型返回不同的信息
      if (error === "format") {
        createMessage("上传图片只能是 JPG/PNG 格式", "error");
      }
      if (error === "size") {
        createMessage("上传图片大小不能超过 1MB", "error");
      }
      return passed;
    };

    const handleFileUploaded = (rawData: ResponseType<ImageProps>) => {
      if (rawData.data._id) {
        imageId = rawData.data._id;
      }
    };

    const onFormSubmit = (result: boolean) => {
      if (result) {
        const { column, _id } = store.state.user;
        if (column) {
          const newPost: PostProps = {
            // id: new Date().getTime(),
            // _id: "",
            title: titleVal.value,
            content: contentVal.value,
            column,
            // createdAt: new Date().toLocaleString(),
            author: _id,
          };
          if (imageId) {
            newPost.image = imageId;
          }
          store.dispatch("createPost", newPost).then(() => {
            createMessage("发表成功，2秒后跳转到文章", "success");
            router.push({ name: "column", params: { id: column } });
          });
          // 自动跳转到详情页
          // store.commit("createPost", newPost);
          // router.push({ name: "column", params: { id: columnId } });
        }
      }
    };
    // const handleFileChange = (e: Event) => {
    //   // 在这个 input 组件中，我们可以拿到他选择的 file对象，也就是文件对象
    //   const target = e.target as HTMLInputElement; // 一个 input 框元素
    //   const files = target.files;
    //   /* 注意这个是一个 files 列表，也就是 fileList 对象，
    //   他是一个 array-link 的 object 的一个类数组的对象，但是不是一个数组，支持选择多个文件
    //   所以他可能有很多 */
    //   if (files) {
    //     // 我们拿到他的第一项，就是我们选择的文件
    //     const uploadedFile = files[0];
    //     // 我们来模拟表单的数据，我们可以使用 FormData 对象，这是另一种针对 XHR2 设计的新数据类型
    //     // 使用 FormData 能够很方便的实现以 JavaScript 创建 HTML
    //     // 表单数据串联化就是 name=zs&age=13 的这种方式
    //     const formData = new FormData(); // 是自带的，是可以直接使用的
    //     // 通过 append 方法为其附加了 <input> 值
    //     // 我们通过 FormData 对象添加了 input 的值
    //     formData.append(uploadedFile.name, uploadedFile);
    //     axios
    //       .post("/upload", formData, {
    //         headers: {
    //           // 设置请求头
    //           "Content-Type": "multipart/form-data",
    //         },
    //       })
    //       .then((resp) => {
    //         console.log(resp);
    //       });
    //   }
    // };
    return {
      titleVal,
      titleRules,
      contentVal,
      contentRules,
      onFormSubmit,
      titleValue,
      contentValue,
      uploadedCheck,
      handleFileUploaded,
    };
  },
});
</script>

<style>
.create-post-page,
.file-upload-container {
  height: 200px;
  cursor: pointer;
  overflow: hidden;
}
.create-post-page,
.file-upload-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.uploaded-area {
  position: relative;
}
.uploaded-area:hover h3 {
  display: block;
}
.uploaded-area h3 {
  display: none;
  position: absolute;
  color: #999;
  text-align: center;
  width: 100%;
  top: 50%;
}
</style>
